
#include <stdarg.h>

#include "../src/public.h"

#include "logs.h"

static int sock_fd=-1;
static struct sockaddr_in sin;
static char r_label[32];

int logs_open(char *label, char *addr, int port)
{
	struct hostent *he;

    sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (-1 == sock_fd)
    {
        perror("socket() error : ");
        exit(1);
    }

	////////////////////////////////////

	bzero(&sin, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_port = htons(port);

	inet_pton(AF_INET, addr, &sin.sin_addr);

	bzero(r_label, sizeof(r_label));
	strncpy(r_label, label, sizeof(r_label)-1);

	return 0;
}

int logs_msg(char *file, char *func, int line, int level, char *fmt, ...)
{
	struct log_msg_t logmsg;
	va_list vl;
	int len;

	bzero(&logmsg, sizeof(logmsg));

	logmsg.magic = LOG_MAGIC;
	logmsg.level = level;
	snprintf(logmsg.label, sizeof(logmsg.label)-1, "%s-%d", r_label, getpid());
	snprintf(logmsg.place, sizeof(logmsg.place)-1, "%s-%s()-%d", file, func, line);
	va_start(vl, fmt);
    len = vsnprintf(logmsg.msg, sizeof(logmsg.msg) - 1, fmt, vl);
    va_end(vl);

	len = sendto(sock_fd, &logmsg, sizeof(logmsg), 0, (struct sockaddr *)&sin, sizeof(sin));
    if (-1 == len)
    {
        perror("sendto() error : ");
        return -1;
    }

	return 0;
}

int logs_close()
{
	close(sock_fd);

	return 0;
}

